/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database;

import java.sql.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.*;

/**
 *
 * @author Stephanie
 */
public class IngredientTable {

    private DatabaseConnection db = new DatabaseConnection();
    private ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
    private Connection connection;
    private Statement statement;
    private ResultSet rs;

    public void establishConnection() {
        db.connect();
    }

    public void cancelConnection() {
        db.disconnect();
    }

    public ArrayList<Ingredient> getIngredients() {
        try {
            this.establishConnection();
            connection = db.getCon();
            statement = connection.createStatement();
            statement.execute("SELECT * FROM Zutat");
            rs = statement.getResultSet();

            Ingredient ingredient;

            if (rs != null) {
                while (rs.next()) {
                    ingredient = new Ingredient(rs.getInt(1), rs.getString(2), rs.getBoolean(3));
                    ingredients.add(ingredient);
                    System.out.println(ingredient.getZutatID() + " " + ingredient.getZutatname());
                }
            }

            this.cancelConnection();

        } catch (SQLException ex) {
            Logger.getLogger(CocktailTable.class.getName()).log(Level.SEVERE, null, ex);
        }
        return ingredients;
    }

    public void setIngredientfirst() {

        this.establishConnection();
        connection = db.getCon();
        try {
            statement = connection.createStatement();
            statement.execute("UPDATE Zutat SET Verfuegbarkeit = " + 0);

            connection.commit();
        } catch (SQLException ex) {
            Logger.getLogger(IngredientTable.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Ingredient saveIngredient(int ingredientid) {
        Ingredient ingredient = null;
        try {
            this.establishConnection();
            connection = db.getCon();

            statement = connection.createStatement();
            statement.execute("UPDATE Zutat SET Verfuegbarkeit = " + true + " WHERE ZutatID = " + ingredientid);
            System.out.println("jetzt verfuegbar: " + ingredientid);
            connection.commit();

            this.cancelConnection();

        } catch (SQLException ex) {
            Logger.getLogger(CocktailTable.class.getName()).log(Level.SEVERE, null, ex);
        }
        return ingredient;
    }
}
